#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: links.py
@contact: zwb15083976291@163.com
@time: 2021/11/21
"""
from django.db.models import Q
from rest_framework import serializers

from common.models import BlogLink
from utils.func import whether_url
from utils.serializers.serializer import SpecifySerializeFieldModelSerializer, UpdateBaseSerializeMethodMixin


class LinkSerializer(UpdateBaseSerializeMethodMixin, SpecifySerializeFieldModelSerializer):
    id = serializers.IntegerField()

    class Meta:
        model = BlogLink
        fields = '__all__'


class LinkSerializerValidate(object):

    def validate_id(self, value):
        link = BlogLink.objects.filter(id=value).first()
        if not link:
            raise serializers.ValidationError("数据不存在")
        return value

    def validate_link_image_url(self, value):
        if whether_url(value):
            return value.strip()
        raise serializers.ValidationError("请输入合法的URL")

    def validate_link_url(self, value):
        if whether_url(value):
            return value.strip()
        raise serializers.ValidationError("请输入合法的URL")


class CreateLinkSerializer(LinkSerializer, LinkSerializerValidate):

    def validate_link_name(self, value):
        if BlogLink.objects.filter(link_name=value).first():
            raise serializers.ValidationError("友链名称已经存在")
        return value


class DeleteLinkSerializer(LinkSerializer, LinkSerializerValidate):
    pass


class PutLinkSerializer(LinkSerializer, LinkSerializerValidate):

    def validate(self, attrs):
        if BlogLink.objects.filter(Q(link_name=attrs.get('link_name')), ~Q(id=attrs.get("id"))).first():
            raise serializers.ValidationError("友链名称已经存在")
        return attrs
